//
//  ViewController.swift
//  Compass
//
//  Created by xmg on 16/8/21.
//  Copyright © 2016年 wlis. All rights reserved.
//

import UIKit
import CoreLocation
class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    
    private lazy var manager : CLLocationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        /** 授权 */
        if #available(iOS 8.0, *) {
            manager.requestWhenInUseAuthorization()
        } else {
            manager = CLLocationManager()
        }
        /** 设置代理 */
        manager.delegate = self
        /** 手机方向 */
        manager.startUpdatingHeading()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension ViewController : CLLocationManagerDelegate{

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        UIView.animateWithDuration(2.5, delay: 0.0, options: [], animations: { () -> Void in
//            self.imageView.frame = 
            }, completion: nil)
    }
    
    func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        /** 获取真北方向 */
        let trueHeading = newHeading.trueHeading
        
        /** 让指南针向南面 */
        let angle  = M_PI / 180 * trueHeading
        /** 创建transform */
        let transform = CGAffineTransformMakeRotation(CGFloat(-angle))
        UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5.0, options: [], animations: { () -> Void in
            self.imageView.transform = transform
            }, completion: nil)
    }
    
    
    
}